import Utils from './utils.js';
import InterceptorManager from './InterceptorManager.js';

function Kxios(config){
  // //初始化参数
  this.config = config;

  //拦截器
  this.interceptors = {
    request: new InterceptorManager(),
    response: new InterceptorManager()
  }
}

Kxios.prototype.request=function(config){

  // 请求需要的配置, 把传入的congig和this.config合并
  let reConfig = Utils.mergeConfig(this.config,config);

  /**
   * this.interceptors.request
   * this.dispatchRequest(config)
   */
  //调用连
  var chian = [this.dispatchRequest,undefined];

  //循环取出请求拦截器内注册的所有函数
  /** 
   * this.interceptors.request.handlers
   * =>[resolve1,reject1,resolve2,reject2]
   * 
   * chain = [resolve2,reject2,resolve1,reject1,this.dispatchRequest,undefined]
  */
  var requestHandlers = this.interceptors.request.handlers;
  var requestHandlersLen = requestHandlers.length;
  for (let i = 0; i < requestHandlersLen; i++) {
    chian.unshift(requestHandlers[i].resolve,requestHandlers[i].reject);
  }

  //响应拦截器是想尾部添加
  /** 
   * this.interceptors.request.handlers
   * =>[resolve1,reject1,resolve2,reject2]
   * 
   * chain = [resolve2,reject2,resolve1,reject1,this.dispatchRequest,undefined,resolve1,reject1,resolve2,reject2]
  */
 var responseHandlers = this.interceptors.response.handlers;
 var responseHandlersLen = responseHandlers.length;
 for (let i = 0; i < responseHandlersLen; i++) {
    chian.push(responseHandlers[i].resolve,responseHandlers[i].reject);
 }

 /** 
  * 请求拦截器后注册的先执行
  * 响应拦截器先注册先执行
 */

 //不去调用chain中的函数，而是创建一个新的resolve状态的promise
 //作为整个调用的其实函数
 var promise = Promise.resolve(reConfig);

 // 把chain中的所有函数添加到promise对象的then中
 while(chian.length){
    promise.then( chian.shift(), chian.shift() );
 }

 //promise.then(f1,f2).then(f2,f3).then(f4,f5).....

 return promise;
}

Kxios.prototype.dispatchRequest = function(config){
  console.log('dispatchRequest方法');
  return new Promise(function(resolve,reject){
    var xhr = new XMLHttpRequest();

    xhr.onload=function(){
      let responseData = {
        data: JSON.parse(this.responseText),
        status: this.status,
        statusText: this.statusText
      }
      resolve(responseData)
    }
  
    xhr.open(config.method, config.url, true);
  
    xhr.send();
  })
}

export default Kxios;